import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Image} from '@tarojs/components'
import {newHttp} from '../../utils/request'
import {MP_USER_QRCODE, MP_USER_INFO} from '../../constants/api'
import {user} from "../../utils/user.service";
import {getTokenFromCookies} from "../../utils/tools";
import './gzh-auth.scss'

export default class JoinWx extends Component<{ sid?: number; phone?: number; title?: string; img?: string }> {
  state: {
    gzhqrcode?: string
    gzhIsSHow?: boolean
  } = {
    gzhqrcode: '',
    gzhIsSHow: false
  }

  async UNSAFE_componentWillMount() {
    if (process.env.P_ENV !== 'lx') {
      if(this.props.fromWhere && this.props.fromWhere === "seckillDetail") return; // 秒杀详情不请求
      const {pkeys = '', defaultSellerLogin = ''} = Taro.getCurrentInstance().router.params
      if (process.env.TARO_ENV == 'h5' && Taro.getStorageSync('user') && process.env.NODE_ENV !== 'development' && !pkeys && !defaultSellerLogin && getTokenFromCookies(document.cookie)) {
        const shareParams = await user.getSellerParams()
        let sceneStr = window.location.href + '&' + shareParams
        if (this.props.title) sceneStr += '&title=' + encodeURIComponent(this.props.title)
        if (this.props.img) sceneStr += '&img=' + this.props.img
        const code = await newHttp.catchGet(MP_USER_QRCODE, {scene_str: sceneStr})
        this.state.gzhqrcode = code.img
        await this.gzhAuthClose()
      }
    }
  }

  // 公众号授权
  async gzhAuthClose() {
    this.setState({gzhIsSHow: false}, async () => {
      const mpUserInfo = await newHttp.catchGet(MP_USER_INFO)
      if (mpUserInfo.subscribe == 1) {
        this.state.gzhIsSHow = false
      } else {
        this.state.gzhIsSHow = mpUserInfo;
      }
      if (mpUserInfo) Taro.setStorageSync('mpUserInfo', mpUserInfo)
      this.setState({gzhIsSHow: this.state.gzhIsSHow})
    })
  }

  render() {
    const {gzhIsSHow, gzhqrcode} = this.state
    return (
      <View className='joinRoot'>
        {gzhIsSHow && process.env.TARO_ENV === 'h5' && <View className='curtainRoot gzh-root'>
          <View className='gzh-box'>
            <Image className='gzh-box-img' src={gzhqrcode} mode='widthFix' />
          </View>
          <View onClick={this.gzhAuthClose.bind(this, true)} className='gzh-close'>
            <Image className='gzh-close-img' src='http://resource.ivcheng.com/resources/weapp/images/gzh-close.png' mode='widthFix' />
          </View>
        </View>}
      </View>
    )
  }
}
